var ROOT = "http://127.0.0.1/tech1.5";
// HELPER FUNCTIONS
function findPosX(obj){ var posLeft = 0; try{ var imageBorderLeft = getComputedStyle(obj, '').getPropertyValue('border-left-width'); var imagePaddingLeft = getComputedStyle(obj, '').getPropertyValue('padding-left'); }catch(e){ var imageBorderLeft = obj.currentStyle.borderLeftWidth; var imagePaddingLeft = obj.currentStyle.paddingLeft; } posLeft += parseFloat(imageBorderLeft); posLeft += parseFloat(imagePaddingLeft); if(obj.offsetParent){ while(1){ posLeft += obj.offsetLeft; if(!obj.offsetParent){ break; } obj = obj.offsetParent; } } else if(obj.x){ posLeft += obj.x; } return posLeft; }
function findPosY(obj){ var posTop  = 0; try{ var imageBorderTop  = getComputedStyle(obj, '').getPropertyValue('border-top-width');  var imagePaddingTop  = getComputedStyle(obj, '').getPropertyValue('padding-top');  }catch(e){ var imageBorderTop  = obj.currentStyle.borderTopWidth;  var imagePaddingTop  = obj.currentStyle.paddingTop;  } posTop  += parseFloat(imageBorderTop);  posTop  += parseFloat(imagePaddingTop);  if(obj.offsetParent){ while(1){ posTop  += obj.offsetTop;  if(!obj.offsetParent){ break; } obj = obj.offsetParent; } } else if(obj.y){ posTop += obj.y;  } return posTop;  }

// DETECT CHARSET OF THE PAGE
function getCharSet() {
   var docCharSet = document.characterSet;
   if (docCharSet === undefined) {
       docCharSet = document.charset;
   }
   if (docCharSet === undefined) {
       docCharSet = document.getElementsByTagName("meta")[0].getAttribute("content").split("=")[1];
   }
   return docCharSet;
}

// DISPLAY A WARNING WINDOW
function whiAlertWindow(thecontent){
    addCss();
    var whiWindow = document.createElement("div");
    whiWindow.setAttribute("id","whi-window");
    whiWindow.innerHTML = "<div class=\"whi-closewindow\" onclick=\"this.parentNode.style.display='none'\">关闭</div>";
    whiWindow.innerHTML += thecontent;

    document.body.appendChild(whiWindow);
}

// GET BASIC INFO
var pageTitle = document.title;
pageTitle = pageTitle.replace("'","").replace("#","").replace("&","_");
if(!pageTitle.length){ pageTitle = "Untitled"; }
var pageUrl = location.href;
var pageTags = "";
// var meta = document.getElementsByTagName("meta");
// for(m=0;m<meta.length;m++){ if(meta[m].name == "keywords"){ pageTags += meta[m].content; } }


// FINDING THE IMAGES
function findImages(){

    var foundImages = document.images;
    var invalidCount = 0;
    var validCount = 0;

    // loop images to validate
    for(i=0;i<foundImages.length;i++){
        var image = foundImages[i];
        if((image.width < 240)
        || (image.height < 200)
        || (image.src.match("spaceball|dot|clear|spacer|pixie|pixel|dont_steal|blank|empty"))
        || (image.name == "gmi-ResViewSizer_fullimg") // deviantart.com
        || (image.style.display == "none") // lookbook.nu
        ){
            // not valid, add one to the invalid count
            invalidCount++;
        }else{
            // it's a valid image, create the button
            validCount++;
            image.setAttribute("class","whi-valid");
            createButton(image);
        }
    }

    // warn invalid images
    if(invalidCount > 0){
        var whiAlert = document.getElementById('whi-alert');
        whiAlert.innerHTML = "没有添加粉色框的图片不能收录！";
    }

    // warn no images found
    if(validCount == 0){
        whiAlertWindow("<strong>对不起</strong> <span>我们没有在这个页面找到可以收录的图片！</span> <a href="+ ROOT +"'/#' target='_blank'>为什么会酱紫？</a>");
    }

}

// CREATING BUTTON OVER IMAGE
function createButton(image){

    var hover = document.createElement("div");

    hover.setAttribute("class","whi-hover");
    hover.style.width = (image.width - 16) + "px";
    hover.style.height = (image.height - 16) + "px";
    hover.style.top = (findPosY(image)) + "px";
    hover.style.left = (findPosX(image)) + "px";

    var hoverHTML = "";
    hoverHTML += "<form action='"+ ROOT +"/favpic.php' method='get' target='_blank' onsubmit='hearted(this)'>";
    hoverHTML += "<input type='hidden' value='fetchpic' name='mod' />";
    hoverHTML += "<input type='hidden' value='" + image.src + "' name='imgurl' />";
    hoverHTML += "<input type='hidden' value='" + getCharSet() + "' name='charset' />";
    // hoverHTML += "<div class='whi-tags'><span>title:</span><input type='text' value='"+ pageTitle +"' name='title' /></div>";
    hoverHTML += "<div class='whi-title'>"+ pageTitle +" <input type='hidden' value='" + pageTitle.replace(/'/g, "&#39;") + "' name='title' /></div>";
    hoverHTML += "<div class='whi-source'>"+ pageUrl +" <input type='hidden' value='" + pageUrl + "' name='weburl' /></div>";
    hoverHTML += "<div class='whi-tags'><span>标签:</span><input type='text' value='" + pageTags + "' placeholder='使用空格分开' name='tags' /></div>";
    hoverHTML += "<div class='whi-submit'>";
    // hoverHTML += "<div class='whi-unsafe'><label><input type='checkbox' value='yes' name='unsafe' /> is it unsafe?</label></div>";
    hoverHTML += "<input type='submit' value='点击远程下载到我的实验室' class='whi-btn' /></div>";
    hoverHTML += "</form>"

    hover.innerHTML = hoverHTML;

    var whiContents = document.getElementById('whi-contents');
    whiContents.appendChild(hover);
}

function hearted(theform){
    theform.setAttribute("class","whi-hearted");
}

// CREATING THE TOP BAR
function createBar(){

    var whiContents = document.createElement("div");
    whiContents.setAttribute("id","whi-contents");
    document.body.appendChild(whiContents);

    var whiCover = document.createElement("div");
    whiCover.setAttribute("id","whi-cover");
    whiContents.appendChild(whiCover);

    var whiBar = document.createElement("div");
    whiBar.setAttribute("id","whi-bar");

    whiBarHTML  = "<div class='whi-text'>可以添加标签，然后点击收录，就可以把这个图片远程下载到实验室您的账号内. <span id='whi-alert'></span></div>";
    whiBarHTML += "<input type='button' value='关闭' onclick='whiClear()' class='whi-close' />";
    whiBarHTML += "<div class='whi-help'><a href='"+ ROOT +"/#' target='_blank'>帮助</a><ul><li><a href='"+ ROOT +"/#' target='_blank'>如何使用</a></li><li><a href='"+ ROOT +"/group/1' target='_blank'>报告错误</a></li><li><a href='"+ ROOT +"/group/1' target='_blank'>讨论和提出新意见</a></li></ul></div>";

    whiBar.innerHTML = whiBarHTML;
    whiContents.appendChild(whiBar);
}

// STYLE IT ALL
function addCss(){
    var whiCss = document.createElement("link");
    whiCss.rel = "stylesheet";
    whiCss.type = "text/css";
    whiCss.href = ROOT + "/static/style/bookmarklet.css";
    whiCss.setAttribute("id","whi-css");
    document.getElementsByTagName("head")[0].appendChild(whiCss);
}

// REMOVE EVERYTHING
function whiClear(){
    // var whiScript = document.getElementById('whi');
    // document.body.removeChild(whiScript);

    var whiContents = document.getElementById('whi-contents');
    document.body.removeChild(whiContents);

    var whiCss = document.getElementById('whi-css');
    document.getElementsByTagName("head")[0].removeChild(whiCss);
}

// MAKE IT HAPPEN
if(pageUrl.match("weheartit.com")){
    whiAlertWindow("<strong>喂喂喂！</strong> <span>在实验室里，你直接点击红心就可以收录了啦！</span> <a href='"+ ROOT +"/#' target='_blank'>需要入门文档？</a>");
}else
if(pageUrl.match("tumblr.com/dashboard|google.com/reader")){
    whiAlertWindow("<strong>喂喂！</strong> <span>有一些网站由于授权或者技术原因，暂时不能收录！</span>");
}else
if(pageUrl.match("vimeo.com|youtube.com")){
    alert("这些网站由于有更好的方式，稍后尝试吧！");
}else
if(!document.getElementById('whi-bar')
&& !pageUrl.match(".jpg|.png|.gif")){
    addCss();
    createBar();
    findImages();
}else
if(document.getElementById('whi-bar')
&& !pageUrl.match(".jpg|.png|.gif")){
    whiClear();
    addCss();
    createBar();
    findImages();
}else
if(pageUrl.match(".jpg|.png|.gif")){
    alert("目前不支持这样的方式直接收录 \n因为将无法获取标签和标题！");
    window.open(ROOT + "/#","whiwindow");
}